//
//  sorts.cpp
//  MyTryForMapping2
//
//  Created by Артемий Соболев on 15.05.12.
//  Copyright (c) 2012 avriy@me.com. All rights reserved.
//


#include "sorts.h"


int intFromCharArrayWithThePlacesAtIndex(char ch[], int places, int index){
    return atoi(&ch[(places+1)*index]);
}

void  writeNumberAtIndexToChar(char ch[], int places, int index, int number){
   char temp[places];
    sprintf(temp, "%d",number);
    for (int i = 0; i < places; i++) ch[(places+1)*index+i] = temp[i];
}

void quickSort(int fd, int count){
    off_t fsize = lseek(fd, 0, SEEK_END);
    char *a;
    int places;
    a = (char *)mmap(NULL, fsize, PROT_WRITE | PROT_READ| PROT_EXEC, MAP_SHARED, fd, 0);    
    if (count<0) places = abs(count) + 1;
    else places = count;
    int endIndex = fsize/(places+1);
    quickSortSupport(a, endIndex-1, places, 0);
    
}

void quickSortSupport(char a[], int right, int places, int left) {
    
    int i = left;
    int j = right;
    int p;
    
    p = intFromCharArrayWithThePlacesAtIndex(a, places, (left+right)/2);
    
    while ( i<=j )
    {
        while ( intFromCharArrayWithThePlacesAtIndex(a, places, i) < p ) i++;
        while ( intFromCharArrayWithThePlacesAtIndex(a, places, j) > p ) j--;
        
        if (i <= j) {
            
            int temp = intFromCharArrayWithThePlacesAtIndex(a, places, i);
            writeNumberAtIndexToChar(a, places, i, intFromCharArrayWithThePlacesAtIndex(a, places, j));
            writeNumberAtIndexToChar(a, places, j, temp);
            i++; j--;
        }
    } 
    if ( left < j ) quickSortSupport(a, j, places, left);
    if ( right > i ) quickSortSupport(a, right, places, i);
    
}

void bubbleSort(int fd, int places){
    if(places<0) places = abs(places)+1;
    off_t fsize = lseek(fd, 0, SEEK_END);
    char *ptr;
    ptr = (char *)mmap(NULL, fsize, PROT_WRITE | PROT_READ| PROT_EXEC, MAP_SHARED, fd, 0);
    if( ptr == MAP_FAILED ) printf("Mapping of tmps failed!\n");
    int indexNumber = fsize/(places+1);
    
    bool t = true;
    while (t) 
    {
        t = false;
        for (int j = 0; j<indexNumber-1; j++) 
        {
            int a = intFromCharArrayWithThePlacesAtIndex(ptr, places, j);
            int b = intFromCharArrayWithThePlacesAtIndex(ptr, places, j+1);
            
            if (a>b) 
            {
                int c = a;
                writeNumberAtIndexToChar(ptr, places, j, b);
                writeNumberAtIndexToChar(ptr, places, j+1, c);
                t = true;
            }
        }
    }
    
    munmap((char *)ptr, fsize); 
    
}
